﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：AutoClassMapper.cs
// 功能描述：TongTongMall.Dapper
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Castle.Components.DictionaryAdapter;
using System;
using System.Reflection;
using TongTongMall.Domain.Repositories.Attributes;

namespace TongTongMall.Dapper.DapperExtensions.Mapper
{
    internal class AutoClassMapper<T> : ClassMapper<T> where T : class, new()
    {
        public AutoClassMapper()
        {
            Type type = typeof(T);
            PropertyInfo identifyProperty = null;
            //做字段处理
            foreach (var property in type.GetProperties())
            {
                if (property.IsDefined(typeof(IdentifyAttribute), false))
                {
                    //联合主键
                    Map(property).Column(property.Name).Key(KeyType.Identity);
                    identifyProperty = property;
                }
                var ignore = property.GetCustomAttribute<IgnoreAttribute>();
                if (property.IsDefined(typeof(IgnoreAttribute), false) && ignore.isIgnore)
                {
                    //标记不是数据库字段
                    Map(property).Ignore();
                }
            }
            if (identifyProperty == null)
            {
                throw new TongTongMallException("请检查实体内是否含有标识列：Name=" + type.Name);
            }
            //todo:tablename解析更改为attribute解析
            //System.ComponentModel.DataAnnotations.Schema
            var tablenameAttribute = (System.ComponentModel.DataAnnotations.Schema.TableAttribute)Attribute.GetCustomAttribute(type, typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute));
            Table(tablenameAttribute.Name ?? type.Name);
            AutoMap();
        }
    }
}
